package com.imooc.aspect;

import com.imooc.constant.CookieConstant;
import com.imooc.constant.RedisConstant;
import com.imooc.exception.SellerAuthorizeException;
import com.imooc.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 功能描述: <br>
 * (【授权切面】，未授权则抛出异常)
 *
 * @Author:Mr. xyb
 * @Date: 2018/5/18 17:28
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Aspect
@Component
@Slf4j
public class SellAuthorizeAspect {


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 配置切点，同时过滤不被拦截的控制器
     */
    @Pointcut("execution(public * com.imooc.controller.Seller*.*(..))" +
            "&& !execution(public * com.imooc.controller.SellerUserController.*(..))")
    public void verify() {
    }

    /**
     * 在切点之前执行
     */
    @Before("verify()")
    public void doVerify() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 从request中查询cookie
        String value = CookieUtils.getCookieValue(request, CookieConstant.TOKEN);
        if (value == null) {// cookie为空
            log.warn("【登录校验】Cookie中查不到token");
            throw new SellerAuthorizeException();
        }
        // 根据cookie中的token的值，去redis中查询token的值
        String token = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX + "%s", value));
        if (StringUtils.isEmpty(token)) {// 如果token为空
            log.warn("【登陆校验】Redis中查不到token");
            throw new SellerAuthorizeException();
        }
    }

}
